#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：api_automation_test 
@File    ：read_file.py
@IDE     ：PyCharm 
@Author  ：XiaoDengYa
@Date    ：2021/7/21/021 16:57 
"""
import json

import yaml

from common.tools import extractor
from common.tools import logger
from common.tools.path_dir import *


class ReadFile(object):
    config_dict = None

    @classmethod
    def get_config_dict(cls, config_name: str = "config.yaml") -> dict:
        """
        读取配置文件，并转换成字典形式
        :param config_name: 文件名（带后缀名）
        :return: cls.config_dict
        """
        config_path = os.path.join(get_subdirectory_path("config"), config_name)
        try:
            if cls.config_dict is None:
                with open(config_path, 'r', encoding='utf-8') as file:
                    cls.config_dict = yaml.load(
                        file.read(), Loader=yaml.FullLoader)
            return cls.config_dict
        except Exception as e:
            logger.error("读取配置文件有误，请检查配置路径是否有误：路径【{}】，错误信息{}".format(config_path, e))

    @classmethod
    def read_config(cls, expr: str = '.') -> dict:
        """默认读取config目录下的config.yaml配置文件，根据传递的expr jsonpath表达式可任意返回任何配置项
        :param expr: 提取表达式, 使用jsonpath语法,默认值提取整个读取的对象
        return 根据表达式返回的值
        """
        return extractor(cls.get_config_dict(), expr)

    @classmethod
    def read_test_case(cls, api_name):
        """
        读取yaml文件格式的测试用例
        :return: data_list - pytest参数化可用的数据
        """
        case = []
        data_name = cls.read_config('$.file_path.case_data')
        data_path = os.path.join(get_subdirectory_path("data"), data_name)
        with open(data_path, mode="r", encoding="utf-8") as f:
            data = yaml.safe_load(f).get(api_name)
        for value in data:
            if value[6] == "yes":
                del value[6]
                case.append(value)
        return case

    @classmethod
    def read_header_data(cls, user_case_name: str) -> dict:
        """
        读取header头部信息
        :param user_case_name: 需要请求的头部信息名称
        :return:
        """
        data_name = cls.read_config("$.file_path.header_data")
        data_path = os.path.join(get_subdirectory_path("data"), data_name)
        with open(data_path, mode="r", encoding="utf-8") as f:
            data = json.load(f)
        return data.get(user_case_name)

    @classmethod
    def update_yaml_data(cls, metadata: str, name: str, data: str, config_name="config.yaml"):
        """
        修改yaml文件配置
        :param config_name: 文件名称
        :param metadata: 需要修改的key
        :param name: 名称
        :param data: 要修改的数据
        :return: None
        """
        config_path = os.path.join(get_subdirectory_path("config"), config_name)
        with open(config_path, 'r', encoding='utf-8') as f:
            # print(f.read())
            result = f.read()
            x = yaml.load(result, Loader=yaml.FullLoader)

            # 修改的值
            x[metadata][name] = data
            print(x)
            with open(config_path, 'w', encoding='utf-8') as w_f:
                # 覆盖原先的配置文件
                yaml.dump(x, w_f)


if __name__ == '__main__':
    # ReadFile().update_yaml_data("promoter_user", "user_name", "1546511")

    print(ReadFile().read_test_case("test_api_auto")[1])